/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-14 下午6:39
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.activities.LoginActivity;
import com.example.dqhl.jdmetro.activities.MyInfoActivity;
import com.example.dqhl.jdmetro.activities.SearchActivity;
import com.example.dqhl.jdmetro.adapter.consulation.ConsultationTabAdapter;
import com.example.dqhl.jdmetro.base.BaseFragment;
import com.example.dqhl.jdmetro.bean.User;
import com.example.dqhl.jdmetro.bean.consulation.ConsultationTab;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.config.Constant;
import com.example.dqhl.jdmetro.fragment.Consulation.ConsultationCommonFragment;
import com.example.dqhl.jdmetro.fragment.Consulation.ConsultationFirstFragment;
import com.example.dqhl.jdmetro.utils.CommonUtil;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.JumpItent;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.readystatesoftware.viewbadger.BadgeView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:资讯汇
 * autour:guanluocang
 * date:17/6/15 13:28
 */
public class ConsultationFragment extends BaseFragment {

    private Context context;
    @Bind(R.id.tv_login)
    TextView tv_login;//左上角登录
    @Bind(R.id.tv_top_title)
    TextView tv_top_title;//头部title
    @Bind(R.id.viewPager)
    ViewPager viewPager;
    @Bind(R.id.tabLayout)
    TabLayout tabLayout;
    //头部Tab
    private List<ConsultationTab> mConsultationTabs;
    private List<Fragment> mFragmentList;
    private List<String> mTabList;

    private ConsultationTabAdapter tabAdapter;
    //第一个Fragment
    private ConsultationFirstFragment consultationFirstFragment;

    @Bind(R.id.iv_top_msg)
    ImageView iv_top_msg;//有上角消息
    private BadgeView badgeView; //消息右上角数字提醒
    @Bind(R.id.et_search)
    EditText et_search;//搜索内容
    @Bind(R.id.tv_search)
    TextView tv_search;

    @Override
    public View initView(LayoutInflater inflater) {
        rootView = inflater.inflate(R.layout.fragment_consultation, null);
        context = getActivity();
        ButterKnife.bind(this, rootView);
        isLogin();
        registerBroadcastReceiver();
        return rootView;
    }

    /**
     * 广播接收者
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_LOGIN_SUCCESS)) {
                user = (User) intent.getExtras().get("user");
                Dlog.e(user.toString());
                tv_login.setVisibility(View.GONE);
            } else if (action.equals(Constant.ACTION_LOGOUT_SUCCESS)) {
                user = null;
                tv_login.setVisibility(View.VISIBLE);
                tv_login.setText(R.string.txt_login);
            }
        }
    };

    /**
     * 注册广播接收者
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_LOGOUT_SUCCESS);
        context.registerReceiver(receiver, intentFilter);
    }

    /**
     * 是否登录
     */
    private void isLogin() {
        if (user != null) {
            tv_login.setVisibility(View.GONE);
            getMsgCount();
        } else {
            tv_login.setVisibility(View.VISIBLE);
            tv_login.setText("登录");
        }
    }

    @Override
    public void initData() {
        tv_top_title.setText(R.string.app_name);
        //设置可以根据viewpage横向滚懂
        LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(getActivity(),
                R.drawable.layout_tabout_divid));
        linearLayout.setDividerPadding(CommonUtil.dip2px(getActivity(), 15));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        initTopTab();

        badgeView = new BadgeView(getContext(), iv_top_msg);
        badgeView.setGravity(Gravity.TOP | Gravity.RIGHT);
        badgeView.setBadgeBackgroundColor(getResources().getColor(R.color.color_white));
        badgeView.setTextColor(getResources().getColor(R.color.colorPrimary));
    }

    @Override
    public void initListener() {
        tv_login.setOnClickListener(this);
        tv_search.setOnClickListener(this);
        iv_top_msg.setOnClickListener(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //TODO
            //获取消息数量
        }
    }


    /**
     * 顶部Tab
     */
    public void initTopTab() {
        if (mFragmentList != null && mFragmentList.size() > 0) {
            return;
        }
        mFragmentList = new ArrayList<>();
        mTabList = new ArrayList<>();
        consultationFirstFragment = new ConsultationFirstFragment();
        mFragmentList.add(consultationFirstFragment);
        RequestParams params = new RequestParams(Config.consulation_topTab);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("首页Tab标签" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    mConsultationTabs = JSON.parseArray(data, ConsultationTab.class);
                    for (int i = 0; i < mConsultationTabs.size(); i++) {
                        ConsultationCommonFragment consultationCommonFragment = new ConsultationCommonFragment();
                        mFragmentList.add(consultationCommonFragment);
                        mTabList.add(mConsultationTabs.get(i).getTheme_name());
                        tabAdapter = new ConsultationTabAdapter(getChildFragmentManager(), mFragmentList, mTabList);
                        //viewpager加载adapter
                        viewPager.setAdapter(tabAdapter);
                        //TabLayout 加载viewpager
                        tabLayout.setupWithViewPager(viewPager);
                        Bundle bundle = new Bundle();
                        if (i == mConsultationTabs.size() - 1) {
                            bundle.putString("theme_id", mConsultationTabs.get(i).getTheme_id());
                        } else {
                            bundle.putString("theme_id", mConsultationTabs.get(i+1).getTheme_id());
                        }
                        consultationCommonFragment.setArguments(bundle);
                    }
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 获取消息数量
     */
    private void getMsgCount() {
        RequestParams params = new RequestParams(Config.info_num);
        params.addBodyParameter("id_auth", user.getId_auth());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("未读消息数:" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (200 == errCode) {
                    String strCount = JsonUtils.getInfo(data, "count");
                    int count = Integer.parseInt(strCount);
                    if (count <= 0) {
                        badgeView.setVisibility(View.GONE);
                    } else {
                        badgeView.setVisibility(View.VISIBLE);
                        badgeView.setText(strCount);
                        badgeView.setTextSize(10);
                        badgeView.show();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login:
                JumpItent.jump(getActivity(), LoginActivity.class);
                break;
            case R.id.tv_search:
                final String searchContent = et_search.getText().toString().trim();
                if (!TextUtils.isEmpty(searchContent)) {
                    RequestParams params = new RequestParams(Config.consulation_search);
                    params.addBodyParameter("content", searchContent);
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            Dlog.e(result);
                            int errCode = JsonUtils.getErrCode(result);
                            String data = JsonUtils.getData(result);
                            if (errCode == 200) {
                                et_search.setText("");
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("searchText", searchContent);
                                JumpItent.jump(getActivity(), SearchActivity.class, bundle);
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {

                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }
                break;
            case R.id.iv_top_msg:
                if (user != null) {
                    JumpItent.jump(getActivity(), MyInfoActivity.class);
                } else {
                    Toastutils.show("请先登录");
                }
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}
